package com.xtjc.recsyslog.netty;

import com.xtjc.recsyslog.netty.decoder.CustomDataDecoder;
import com.xtjc.recsyslog.netty.encoder.CustomDataEncoder;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.timeout.IdleStateHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Component
@Slf4j
public class NettyServerInitializer extends ChannelInitializer<SocketChannel> {

    @Autowired
    private NettyHandler nettyHandler;

    @Override
    protected void initChannel(SocketChannel socketChannel) throws Exception {
        ChannelPipeline pipeline = socketChannel.pipeline();
        // 字符串编解码器
//        pipeline.addLast("decoder", new ByteArrayDecoder());
//        pipeline.addLast("encoder", new ByteArrayEncoder());
        pipeline.addLast(new CustomDataDecoder());
        pipeline.addLast(new CustomDataEncoder());
        //IdleStateHandler心跳机制,如果超时触发Handle中userEventTrigger()方法
        pipeline.addLast("idleStateHandler", new IdleStateHandler(15, 0, 0, TimeUnit.MINUTES));
        //拆包这个是重点 自定义Handler
        pipeline.addLast(nettyHandler);
    }

}